package com.caigou.modules.rank.ext

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

/**
 * @author #Suyghur.
 * Created on 2022/02/22
 */

private val nd = 24 * 60 * 60 * 1000L
private val nh = 60 * 60 * 1000L
private val nm = 60 * 1000L
private val ns = 1000L

fun countDownCoroutines(
    startDate: Long,
    scope: CoroutineScope,
    onTick: (String) -> Unit,
    onStart: (() -> Unit)? = null,
    onFinish: (() -> Unit)? = null
): Job {
    return flow {
        while (true) {
            val diff = startDate - System.currentTimeMillis()
            val day = diff / nd
            val hour = diff % nd / nh
            val min = diff % nd % nh / nm
            val sec = diff % nd % nh % nm / ns
            emit("距离月榜截止时间${day}天 $hour:$min:$sec")
            delay(1000L)
        }
    }.flowOn(Dispatchers.Main)
        .onStart { onStart?.invoke() }
        .onCompletion { onFinish?.invoke() }
        .onEach { onTick.invoke(it) }
        .launchIn(scope)
}